//
//  MainViewController.m
//  LogisticsFollow
//
//  Created by JustFei on 2016/12/15.
//  Copyright © 2016年 manridy. All rights reserved.
//

#import "MainViewController.h"
#import "MyOrderViewController.h"
#import "MeViewController.h"
#import "BJNoDataView.h"
#import "OrderTableViewCell.h"
#import "OrderModel.h"
#import "MJRefresh.h"
#import <CoreLocation/CoreLocation.h>
#import "UserInfoModel.h"
#import "FMDBTool.h"
#import "OrderParticularsViewController.h"
#import "SignForViewController.h"

typedef enum : NSUInteger {
    PostTypeStart = 0,
    PostTypeEnd,
    PostTypeMid
} PostType;

@interface MainViewController () < UITableViewDelegate , UITableViewDataSource , CLLocationManagerDelegate >
{
    //CLLocationManager *_locationManager;
//    BOOL _startPost;
//    BOOL _endPost;
//    NSInteger _complete;
    //startPost实在开始配送时置为yes，
    //endPost在结束该次配送时置为yes，
    BOOL haveUnfinishOrder;
    BOOL isStopGPSGet;
}
@property (weak, nonatomic) IBOutlet UIView *locationBackView;
@property (weak, nonatomic) IBOutlet UILabel *currentLocationLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *myOrderView;
@property (nonatomic ,strong) NSMutableArray *dataArr;
@property (nonatomic ,strong) FMDBTool *myFmdbTool;
@property (nonatomic ,strong) MBProgressHUD *hud;
@property (nonatomic ,strong) CLLocationManager *locMgr;
@property (nonatomic ,strong) CLLocation *lastLoc;
@property (nonatomic ,strong) CLLocation *nowLoc;
@property (nonatomic ,strong) NSMutableArray *lastPostArr;
@property (nonatomic ,strong) OrderResultModel *lastPost;
@property (nonatomic ,strong) NSTimer *postTime;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    _startPost = NO;
//    _endPost = NO;
    [self createUI];
    //请求用户信息
    [self getUserInfoDataFromNet];
    //获取未完成的订单数据
    [self getUnfinishOrderData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [[self.navigationController.navigationBar subviews].firstObject setAlpha:0];
    self.navigationController.navigationBar.barTintColor = kClearColor;
    //请求一次位置信息就关闭gps
    isStopGPSGet = YES;
    [self getLocation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createUI
{
    self.locationBackView.layer.cornerRadius = 10;
    self.locationBackView.layer.masksToBounds = YES;
    
    self.navigationItem.title = @"司机任务";
    self.navigationController.navigationBar.tintColor = kWhiteColor;
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = XXF_CGRectMake(0, 0, 44, 42);
    [rightButton setImage:[UIImage imageNamed:@"me"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(showMeVC:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"OrderTableViewCell" bundle:nil] forCellReuseIdentifier:@"orderCell"];
    self.tableView.estimatedRowHeight = 400;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //Call this Block When enter the refresh status automatically
        [self getUnfinishOrderData];
    }];
    
    [self addObserver:self forKeyPath:@"dataArr" options:NSKeyValueObservingOptionNew context:nil];
    self.dataArr=[NSMutableArray array];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showMyOrder:)];
    [self.myOrderView addGestureRecognizer:tap];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = backItem;
}

- (void)getUserInfoDataFromNet
{
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    //参数guid：用户id
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    NSString *guid = [[NSUserDefaults standardUserDefaults] objectForKey:@"guid"];
    [parametersDic setObject:guid forKey:@"guid"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //用户信息请求
    [manager POST:kUserInfoPort parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        //json解析
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //转成jsonModel
        UserInfoModel *model = [[UserInfoModel alloc] initWithDictionary:resultDic error:nil ];
        NSLog(@"isSuccess = %d\nmsg = %@",model.isSuccess ,model.msg);
        if (model.isSuccess) {
            UserInfoResultModel *resultModel = model.result[0];
            //TODO:这里需要判断下数据库中是否有该数据，或者将数据库中的数据以新的数据进行替代
            [self saveUserData:resultModel];
        }else {
            //                [self doFailGetUserData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        //            [self doFailGetUserData];
    }];
}

- (void)getLocation
{
    DLog(@"获取一次坐标");
    //判断用户定位服务是否开启
    if ([CLLocationManager locationServicesEnabled]) {
        //开始定位用户的位置
        [self.locMgr startUpdatingLocation];
    }else{//不能定位用户的位置
        //1.提醒用户检查当前的网络状况
        //2.提醒用户打开定位开关
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"提示" message:@"请开启定位服务，否则可能无法操作订单！" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *okAc = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:nil];
        [vc addAction:okAc];
    }
}

- (void)saveUserData:(UserInfoResultModel *)model
{
    [self.myFmdbTool insertUserInfoModel:model];
}

- (void)postMidGps
{
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    NSString *guid = [[NSUserDefaults standardUserDefaults] objectForKey:@"guid"];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:guid forKey:@"guid"];
    [parametersDic setObject:[NSNumber numberWithFloat:self.nowLoc.coordinate.longitude] forKey:@"positionX"];
    [parametersDic setObject:[NSNumber numberWithFloat:self.nowLoc.coordinate.latitude] forKey:@"positionY"];
    [parametersDic setObject:self.currentLocationLabel.text forKey:@"address"];
    double distance = [self.lastLoc distanceFromLocation:self.nowLoc];
    [parametersDic setObject:[NSString stringWithFormat:@"%.2f",distance] forKey:@"distance"];
    [parametersDic setObject:self.lastPost.orderId forKey:@"orderId"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:kGPSAddPort parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        //json解析
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //转成jsonModel
        NSError *error = [[NSError alloc] init];
        OrderModel *model = [[OrderModel alloc] initWithDictionary:resultDic error:&error];
        NSLog(@"isSuccess = %d\nmsg = %@",model.isSuccess ,model.msg);
        if (model.isSuccess) {
        }else {
            [self doFailPOST];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [self doFailPOST];
    }];
}

//开始订单提交接口
- (void)startOrderPostWith:(NSInteger)section
{
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    NSString *guid = [[NSUserDefaults standardUserDefaults] objectForKey:@"guid"];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:guid forKey:@"guid"];
    [parametersDic setObject:[NSNumber numberWithFloat:self.nowLoc.coordinate.longitude] forKey:@"positionX"];
    [parametersDic setObject:[NSNumber numberWithFloat:self.nowLoc.coordinate.latitude] forKey:@"positionY"];
    [parametersDic setObject:self.currentLocationLabel.text forKey:@"address"];
    double distance = [self.lastLoc distanceFromLocation:self.nowLoc];
    [parametersDic setObject:[NSString stringWithFormat:@"%.2f",distance] forKey:@"distance"];
    [parametersDic setObject:self.lastPost.orderId forKey:@"orderId"];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:kSatrtPort parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //转成jsonModel
        NSError *error = [[NSError alloc] init];
        OrderModel *model = [[OrderModel alloc] initWithDictionary:resultDic error:&error];
        NSLog(@"isSuccess = %d\nmsg = %@",model.isSuccess ,model.msg);
        if (model.isSuccess) {
            self.hud.label.text = @"提交成功";
            [self.hud hideAnimated:YES afterDelay:1];
            //开启定时器
            [self.postTime setFireDate:[NSDate distantPast]];
            OrderResultModel *model =  self.dataArr[section];
            model.status = 1;
            [self.dataArr replaceObjectAtIndex:section withObject:model];
            [self.tableView reloadData];
            self.lastPost = model;
        }else {
            [self doFailPOST];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [self doFailPOST];
    }];
    //将现在历史坐标和现在的坐标对换
    self.lastLoc = self.nowLoc;
}

- (void)endOrderPostWith:(NSInteger)section
{
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    NSString *guid = [[NSUserDefaults standardUserDefaults] objectForKey:@"guid"];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:guid forKey:@"guid"];
    [parametersDic setObject:[NSNumber numberWithFloat:self.nowLoc.coordinate.longitude] forKey:@"positionX"];
    [parametersDic setObject:[NSNumber numberWithFloat:self.nowLoc.coordinate.latitude] forKey:@"positionY"];
    [parametersDic setObject:self.currentLocationLabel.text forKey:@"address"];
    double distance = [self.lastLoc distanceFromLocation:self.nowLoc];
    [parametersDic setObject:[NSString stringWithFormat:@"%f",distance] forKey:@"distance"];
    [parametersDic setObject:self.lastPost.orderId forKey:@"orderId"];
    //[self startLocationPost:parametersDic withType:PostTypeEnd];
    SignForViewController *vc = [[SignForViewController alloc] initWithNibName:@"SignForViewController" bundle:nil];
    vc.parametersDic = parametersDic;
    
    //完成上传回调
    vc.completeUploadOrderInfoBlock = ^ {
        //刷新界面
        [self.dataArr removeObjectAtIndex:section];
        [self.tableView reloadData];
        //停止定时器
        [self.locMgr stopUpdatingLocation];
        [self.postTime invalidate];
        self.postTime = nil;
    };
    [self.navigationController pushViewController:vc animated:YES];
    //将现在历史坐标和现在的坐标对换
    self.lastLoc = self.nowLoc;
}

//获取未完成订单
- (void)getUnfinishOrderData
{
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //服务器给的域名
    NSString *domainStr = kNewOrderPort;
    //创建一个可变字典
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    NSString *guid = [[NSUserDefaults standardUserDefaults] objectForKey:@"guid"];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:guid forKey:@"guid"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
    [manager POST:domainStr parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        //json解析
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //转成jsonModel
        NSError *error = [[NSError alloc] init];
        OrderModel *model = [[OrderModel alloc] initWithDictionary:resultDic error:&error];
        
        //判断订单里是否有正在执行的订单
        for (OrderResultModel *resultModel in model.result) {
            if (resultModel.status == 1) {
                self.lastPost = resultModel;
                haveUnfinishOrder = YES;
                //开启定时器
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    isStopGPSGet = NO;
                    [self getLocation];
                    if (![self.currentLocationLabel.text isEqualToString:@"正在定位"]) {
                        //[self.postTime fire];
                        [self.postTime setFireDate:[NSDate distantPast]];
                    }
                });
                
                break;
            }
        }
        
        NSLog(@"isSuccess = %d\nmsg = %@",model.isSuccess ,model.msg);
        //未完成订单查询完成，刷新列表
        if (model.isSuccess) {
            self.dataArr = [NSMutableArray arrayWithArray:model.result];
            [self.tableView reloadData];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.tableView.mj_header endRefreshing];
            });
        }else {
            [self doFailPOST];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [self doFailPOST];
    }];
}

//开始送货
//- (BOOL)startLocationPost:(NSMutableDictionary *)parametersDic withType:(PostType)start
//{
//    // 启动系统风火轮
//    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//    
//    NSString *domainStr;
//    switch (start) {
//        case PostTypeStart:
//            domainStr = kSatrtPort;
//            NSLog(@"开始");
//            break;
//        case PostTypeEnd:
//        {
//            domainStr = kEndPort;
//            NSLog(@"结束");
//
//            return NO;  //暂时先返回NO
//        }
//            break;
//        case PostTypeMid:
//            domainStr = kGPSAddPort;
//            NSLog(@"中途");
//        default:
//            break;
//    }
//    __block BOOL result = YES;
//    
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
//        // 创建信号量
//        dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
//        [manager POST:domainStr parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            // 隐藏系统风火轮
//            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//            
//            //json解析
//            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
//            //转成jsonModel
//            NSError *error = [[NSError alloc] init];
//            OrderModel *model = [[OrderModel alloc] initWithDictionary:resultDic error:&error];
//            NSLog(@"isSuccess = %d\nmsg = %@",model.isSuccess ,model.msg);
//            if (model.isSuccess) {
//                result = YES;
//                self.hud.label.text = @"提交成功";
//                [self.hud hideAnimated:YES afterDelay:1];
//                if (start == PostTypeEnd) {
//                    [self.dataArr removeObjectAtIndex:_complete];
//                    [self.tableView reloadData];
//                }
//            }else {
//                result = NO;
//                [self doFailPOST];
//            }
//            dispatch_semaphore_signal(semaphore);
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
//            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//            [self doFailPOST];
//            result = NO;
//            dispatch_semaphore_signal(semaphore);
//        }];
//        // 在网络请求任务成功之前，信号量等待中
//    //信号量没搞定
////        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//
//    return result;
//}

- (void)doFailPOST
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
    });
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.mode = MBProgressHUDModeText;
    self.hud.label.text = @"请求失败，请确认网络后重试";
    [self.hud hideAnimated:YES afterDelay:1.5];
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"orderCell"];
    
    cell.model = self.dataArr[indexPath.section];
    __weak __typeof(self) weakSelf = self;
    //开始订单
    cell.startLocationBlock = ^(void){
        if (!haveUnfinishOrder) {
            weakSelf.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            weakSelf.hud.label.text = @"正在提交。。";
            self.lastPost = self.dataArr[indexPath.section];

            //打开定位
            isStopGPSGet = NO;
            [self getLocation];
            //开始订单提交
            [self startOrderPostWith:indexPath.section];

        }else {
            weakSelf.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            weakSelf.hud.label.text = @"当前有未完成的订单，请先完成";
            [weakSelf.hud hideAnimated:YES afterDelay:2];
//            return NO;
        }
    };
    
    //结束订单
    cell.endLocationBlock = ^(void){
        weakSelf.lastPost = self.dataArr[indexPath.section];
        [self endOrderPostWith:indexPath.section];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = kUIColorFromHEX(0xf5f6f6, 1);
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 370;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    OrderResultModel *model = self.dataArr[indexPath.section];
    OrderParticularsViewController *vc = [[OrderParticularsViewController alloc] init];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}



#pragma mark - CLLocationManagerDelegate
/**
 *  当定位到用户的位置时，就会调用（调用的频率比较频繁）
 */
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    //locations数组里边存放的是CLLocation对象，一个CLLocation对象就代表着一个位置
    CLLocation *loc = [locations firstObject];
    self.nowLoc = loc;
    //DLog(@"loc = %@",loc);
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:self.nowLoc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark * place in placemarks) {
            // 国家：place.country;城市：place.locality;区：place.subLocality;街道：place.thoroughfare;子街道：place.subThoroughfare
            NSString *address = [NSString stringWithFormat:@"%@%@%@",place.locality ,place.subLocality ,place.thoroughfare];
            NSLog(@"位置：%@",address);
            //移除null字符
            address = [address stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
            self.currentLocationLabel.text = address;
            //如果需要关闭（只获取一次GPS的情况），就关闭定位信息
            if (isStopGPSGet == YES) {
                [self.locMgr stopUpdatingLocation];
            }
        }
        
    }];
}

#pragma mark - KVO回调
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if (![keyPath isEqualToString:@"dataArr"]) {
        return;
    }
    
    if ([self.dataArr count] == 0) {//无数据
        [[BJNoDataView noDataView] showCenterWithSuperView:self.tableView icon:nil];
        
        return;
    }
    
    //有数据
    [[BJNoDataView noDataView] clear];
}

- (void)dealloc
{
    @try {
        DLog(@"removeObserver");
        [self removeObserver:self forKeyPath:@"dataArr"];
    }
    @catch (NSException *exception) {
        DLog(@"error");
    }
    
}

#pragma mark - Action
- (void)showMyOrder:(UITapGestureRecognizer *)sender
{
    MyOrderViewController *vc = [[MyOrderViewController alloc] init];
    if (self.dataArr.count != 0) {
        vc.dataArr = self.dataArr;
    }
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)showMeVC:(UIButton *)sender
{
    MeViewController *vc = [[MeViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 懒加载
- (FMDBTool *)myFmdbTool
{
    if (!_myFmdbTool) {
        NSString *guid = [[NSUserDefaults standardUserDefaults] objectForKey:@"guid"];
        _myFmdbTool = [[FMDBTool alloc] initWithPath:guid];
    }
    
    return  _myFmdbTool;
}

-(CLLocationManager *)locMgr
{
    if (_locMgr==nil) {
        //1.创建位置管理器（定位用户的位置）
        _locMgr=[[CLLocationManager alloc]init];
        _locMgr.pausesLocationUpdatesAutomatically = NO;
        //弹出允许定位的alert
#ifdef __IPHONE_8_0
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            [_locMgr requestAlwaysAuthorization];
            [_locMgr setAllowsBackgroundLocationUpdates:YES];
        }
#endif
        
        //2.设置代理
        _locMgr.delegate=self;
    }
    return _locMgr;
}

- (NSTimer *)postTime
{
    if (!_postTime) {
        _postTime =  [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(postMidGps) userInfo:nil repeats:YES];
        
        [self.postTime setFireDate:[NSDate distantFuture]];  //先暂停定时器，当应用程序进入后台后再打开。这可根据需求进行修改。
    }
    
    return _postTime;
}

- (NSMutableArray *)lastPostArr
{
    if (!_lastPostArr) {
        _lastPostArr = [NSMutableArray array];
    }
    
    return _lastPostArr;
}

@end
